<?php

namespace app\index\controller;

use app\BaseController;
use app\model\Folder;
use app\model\Image;
use app\model\Image as ModelImage;
use app\model\UserInfo;
use think\exception\ErrorException;
use think\facade\Db;


class Manager extends BaseController
{
    function index(): string
    {
        $user = $this->getUser(true);
        $list = Folder::where("uid", $user['uid'])->order('id', 'desc')->select();
        return $this->fetch('manager/index', ['title' => '控制台', 'list' => $list]);
    }

    function createFolderTemplate(): string
    {
        return $this->fetch('manager/createFolder');
    }

    function move(): \think\response\Json
    {
        $user = $this->getUser();
        $id = $this->request->post('id');
        $folder = $this->request->post('folder');
        $ids = [];
        if ($id) {
            $ids = explode(",", $id);
        }
        $file = ModelImage::where("uid", $user['uid'])->whereIn("id", $ids)->update(['update_time' => date("Y-m-d h:i:s"), "folder" => (int)$folder]);
        if ($file) {
            return $this->success("移动成功");
        }
        return $this->error("移动失败");
    }

    function del(): \think\response\Json
    {
        $user = $this->getUser();
        $id = $this->request->post('id', "");
        $ids = explode(',', $id);
        $file = ModelImage::where("uid", $user['uid'])->whereIn("id", $ids)->select();
        if (count($file) == 0) {
            return $this->error("删除失败");
        }
        foreach ($file as $v) {
            $fileLinkPath = env('FileSystem.root') . '/' . $v['path'];
            try {
                unlink($fileLinkPath);
            } catch (\ErrorException $e) {
                //file not found
            }
            $v->delete();
        }
        $uid = $user['uid'];
        $sql = <<<EOF
            update user_info
            set
                use_store = (select SUM(image.size) from image where user_info.uid = image.uid),
                files_num = (select count(image.id) from image where user_info.uid = image.uid)
            where uid = $uid;
          EOF;
        Db::query($sql);
        return $this->success('删除成功');
    }

    function FolderDel(): \think\response\Json
    {
        $user = $this->getUser(true);
        $id = $this->request->post('id', false);
        if ($id) {
            Db::startTrans();
            try {
                Folder::where("uid", $user['uid'])->where('id', $id)->delete();
                $file = Image::where("uid", $user['uid'])->where('folder', $id)->select();
                foreach ($file as $v) {
                    $fileLinkPath = env('FileSystem.root') . '/' . $v['path'];
                    if (file_exists($fileLinkPath)) {
                        unlink($fileLinkPath);
                    }
                    $v->delete();
                }
                Db::commit();
                return $this->success('删除成功');
            } catch (ErrorException $e) {
                Db::rollback();
            }
        }
        return $this->success('删除失败');
    }

    function createFolder(): \think\response\Json
    {
        $user = $this->getUser(true);
        $name = $this->request->post('name', "");
        $id = $this->request->post('id', false);
        if ($id) {
            $list = Folder::where("uid", $user['uid'])->where('id', $id)->find();
        } else {
            $list = new Folder;
            if (Folder::where('uid', $user['uid'])->where('name', $name)->find()) {
                return $this->error('已存在同名文件夹');
            }
        }
        $list->name = $name;
        $list->uid = $user['uid'];
        $list->save();
        return $this->success('创建成功');
    }

    function folder(): string
    {
        $user = $this->getUser(true);
        $page = $this->request->get('page', 1);
        $folder = $this->request->get('folder', 0);
        $folderInfo = Folder::where("id", $folder)->find();
        $list = Image::where("folder", $folder)->where('uid', $user['uid'])->order('update_time', 'desc')->order("id", "desc")->paginate(18, true);
        $this->assign('title', (isset($folderInfo['name']) ? ($folderInfo['name'] . '-') : '默认目录' . '-') . '文件管理');
        $this->assign('list', $list);
        $userinfo = UserInfo::where('uid', $user['uid'])->find();
        $this->assign("userinfo", $userinfo);
        return $this->fetch('manager/folder', ['folder' => $folder, 'page' => $page]);
    }
}